<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" @cancel="handleClose">
    <a-upload-dragger v-model:fileList="upFileList" name="file" :multiple="true" :action="action" :headers="headers"
      :before-upload="handleBeforeUpload" @change="uploadChange">
      <p class="ant-upload-drag-icon">
        <inbox-outlined></inbox-outlined>
      </p>
      <p class="ant-upload-text">点击或拖拽文档到此处上传</p>
      <p class="ant-upload-hint">仅支持文档类型：.jpge、.png、.doc、.docx、.ppt、.xls、.xlsx，文档大小不超过 200M</p>
    </a-upload-dragger>
    <template #footer>
      <a-button @click="handleClose">关闭</a-button>
    </template>
  </a-modal>
</template>
<script setup name="FileUpload">
import { message, notification } from 'ant-design-vue'
import { config, tool } from 'elead-ui-tool-v3'
const headers = {
  token: config.TOKEN_PREFIX + tool.data.get('TOKEN'),
  Authorization: config.TOKEN_PREFIX + tool.data.get('TOKEN')
}
const emits = defineEmits(['successful', 'change'])
const action = ref()
const visible = ref(false)
const title = ref()
const upFileList = ref([])
const directory = ref()
const oneData = ref(false)
const props = defineProps({
  folderType: {
    type: String,
    default: ''
  },
  formData: {
    md5: String,
    ossBucketName: String,
    ossObjectName: String,
    type: Object,
    uploadFileName: String,
    empId: Number,
    size: Number
  }
})
let fdata = ref({
  md5: String,
  ossBucketName: String,
  ossObjectName: String,
  type: Object,
  uploadFileName: String,
  empId: Number,
  size: Number
})
onMounted(() => {
  if (props.formData) {
    fdata.value = props.formData
  }
})
const uploadChange = ({ file }) => {
  // 将上传变化事件抛出，由父组件处理具体逻辑
  emits('change', { file, oneData: oneData.value, upFileList: upFileList.value })
}
const handleBeforeUpload = (file, fileList) => {
  if (file.size > 1024 * 1000 * 100 * 3) {
    message.error('上传文档大小不能大于300M！')
    handleClose()
    return false
  }
  if (oneData.value && (fileList.length > 1 || upFileList.value.length > 0)) {
    upFileList.value = []
    handleClose()
    message.error('只能上传一个文档！')
    return false
  }
}
/**
 * 关闭上传窗口
 */
const handleClose = () => {
  visible.value = false
  upFileList.value = []
  emits('successful')
}
/**
 * 打开上传窗口
 * @param d {{id: number, folder: string}} 目录id
 */
const onOpen = (d, saveData, fileNumber, version) => {
  if (d) {
    oneData.value = !saveData
    upFileList.value = []
    directory.value = d
    title.value = `上传文档到【${d.folder}】`
    action.value = `${__APP_ENV__.VITE_API_BASEURL}/${props.folderType}/file/upload/${d.id}/${saveData}/${fileNumber}/${version}`
    visible.value = true
  } else {
    notification.error({ message: '缺少目录' })
  }
}
defineExpose({
  onOpen,
  handleClose
})
</script>
<style scoped></style>
